﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Portal.Core.Utils;
using Portal.Data.Entity;

public partial class Admin_Tool : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void OnBookByAuthor(object sender, EventArgs e)
    {
        using (var context = new CmsDataContext())
        {
            //first truncate table
            context.ExecuteCommand("truncate table BookByAuthor");

            //second get list AuthorId
            var authorIds = context.Authors.Select(x => x.ID);
            foreach (var aid in authorIds)
            {
                var books = context.Books.Where(x => x.AuthorId == aid).Select(x => x.ID).ToArray();
                if (books.Any())
                {
                    var bookIds = string.Join(",", books);
                    context.ExecuteCommand("insert into BookByAuthor(AuthorId,BookIds) values ({0},{1})", aid, bookIds);
                }
            }
        }
        ltrMsg.Text = "OnBookByAuthor: Xong";
    }

    protected void OnBookByType(object sender, EventArgs e)
    {
        using (var context = new CmsDataContext())
        {
            //first get list TypeId
            var typeIds = context.HistoryTypes.ToList();
            foreach (var t in typeIds)
            {
                HistoryType t1 = t;
                var books = context.Books.Where(x => ("," + x.Types + ",").Contains("," + t1.FullName + ",")).Select(x => x.ID).ToArray();
                if (books.Any())
                {
                    var bookIds = string.Join(",", books);
                    context.ExecuteCommand("DELETE From BookType Where TypeId={0}", t.ID);
                    context.ExecuteCommand("insert into BookType(TypeId,BookIds) values ({0},{1})", t.ID, bookIds);
                }
            }
        }
        ltrMsg.Text = "OnBookByType: Xong";
    }

    protected void OnHistoryType(object sender, EventArgs e)
    {
        using (var context = new CmsDataContext())
        {
            var all = context.HistoryTypes.ToList();
            foreach (var ht in all)
            {
                context.ExecuteCommand("update HistoryType set SafeName={0} Where Id={1}", BaseObject.GetSafeName(ht.FullName), ht.ID);
            }
        }
        ltrMsg.Text = "OnBookByType: Xong";
    }

    protected void OnUpdateAuthor(object sender, EventArgs e)
    {
        using (var context = new CmsDataContext())
        {
            var all = context.Authors.ToList();
            foreach (var item in all)
            {
                item.SafeName = BaseObject.GetSafeName(item.FullName);
                item.SortName = BaseObject.GetSortNameFromSafeName(item.SafeName);
                context.ExecuteCommand("update Author set SafeName={0},SortName={1} Where Id={2}", item.SafeName, item.SortName, item.ID);
            }
        }
        ltrMsg.Text = "OnUpdateAuthor: Xong";
    }

    protected void OnUpdateBook(object sender, EventArgs e)
    {
        using (var context = new CmsDataContext())
        {
            var all = context.Books.ToList();
            foreach (var item in all)
            {
                Book item1 = item;
                item1.SafeName = BaseObject.GetSafeName(item1.FullName);
                item1.SortName = BaseObject.GetSortNameFromSafeName(item1.SafeName);

                var lastChap =
                    context.Contents.Where(x => x.Book_ID == item1.ID).OrderByDescending(x => x.Chapter).FirstOrDefault();
                var lastChapId = lastChap != null ? lastChap.ID : 0;
                context.ExecuteCommand("update Book set SafeName={0},SortName={1},LastChapId={2} Where Id={3}", item1.SafeName, item1.SortName, lastChapId, item1.ID);
            }
        }
        ltrMsg.Text = "OnUpdateBook: Xong";
    }

    protected void OnUpdateContent(object sender, EventArgs e)
    {
        using (var context = new CmsDataContext())
        {
            var all = context.Contents.Where(x => x.SafeNameBook == null || x.SafeNameBook.Length == 0).ToList();
            foreach (var item in all)
            {
                item.SafeName = BaseObject.GetSafeName(item.Title);
                item.SafeNameBook = context.Books.Where(x => x.ID == item.Book_ID).Select(x => x.SafeName).FirstOrDefault() ?? "";
                context.ExecuteCommand("update Content set SafeName={0},SafeNameBook={1} Where Content_Id={2}", item.SafeName, item.SafeNameBook, item.ID);
            }
        }
        ltrMsg.Text = "OnUpdateContent: Xong";
    }

    protected void OnReBookType(object sender, EventArgs e)
    {
        using (var context = new CmsDataContext())
        {
            var all = context.Books.ToList();
            foreach (var item in all)
            {
                Book item1 = item;
                item1.Types = GetTypes(item1.CrawlUrl);
                if (item1.Types.Length > 0)
                {
                    var typeIds = HistoryType.GetIds(item1.Types);
                    item1.HistoryTypeIds = string.Join(",", typeIds);
                    context.ExecuteCommand("update Book set Types={0},HistoryTypeIds={1} Where Id={2}", item1.Types, item1.HistoryTypeIds, item1.ID);
                    //make list BookByType
                    foreach (var hid in typeIds)
                    {
                        BookType.AddBook(hid, item1.ID);
                    }
                }
            }
        }
        ltrMsg.Text = "OnReBookType: Xong";
    }

    const string OpenTag = "<section id=\"main-left\"";
    const string CloseTag = "</section>";
    const string OpenInfo = "<div class=\"description";
    const string CloseInfo = "</div>";
    string GetTypes(string url)
    {
        var sources = Portal.Data.Crawler.Common.GetHtmlSources(url);
        if (sources.Length > 0)
        {
            var parser = new Portal.Data.Crawler.HtmlParser();
            sources = parser.Replace(sources, HtmlParser.Patterns.BREAK, " ");
            var ss = parser.GetContentInNode(sources, OpenTag, CloseTag);
            if (ss.Count > 0)
            {
                var s = ss[0];
                var infos = parser.GetContentInNode(s, OpenInfo, CloseInfo);
                if (infos.Count > 0)
                {
                    var allElem = parser.GetBetweenTag(infos[0], "p");
                    foreach (Match m in allElem)
                    {
                        var cleartext = HttpUtility.HtmlDecode(parser.RemoveAllTag(m.Value));
                        if (parser.Matched(cleartext, "(thể loại|types)"))
                        {
                            var alltags = parser.GetBetweenTag(m.Value, "a");
                            if (alltags.Count > 0)
                            {
                                var types = alltags.Cast<Match>().Aggregate("", (current, match) => current + (match.Groups[3].Value + ","));
                                return types.Remove(types.Length - 1);
                            }
                            break;
                        }
                    }
                }
            }
        }
        return "";
    }

    protected void OnUpdateImage(object sender, EventArgs e)
    {
        var parser = new Portal.Data.Crawler.HtmlParser();
        using (var context = new CmsDataContext())
        {
            var all = context.Books.Where(x => x.CrawlHost == "blogtruyen" && x.Image.Contains("18.jpg")).ToList();
            foreach (var item in all)
            {
                var sources = Portal.Data.Crawler.Common.GetHtmlSources(item.CrawlUrl);
                if (sources.Length > 0)
                {
                    sources = parser.Replace(sources, HtmlParser.Patterns.BREAK, " ");
                    var blocks = parser.GetContentInNode(sources, "<div class=\"thumbnail", "</div>");
                    if (blocks.Count > 0)
                    {
                        var img = Portal.Data.Crawler.Common.GetFirstImg(blocks[0]);
                        if (!string.IsNullOrEmpty(img))
                        {
                            context.ExecuteCommand("update Book set Image={0} Where Id={1}", img, item.ID);
                        }
                    }
                }
            }
        }
        ltrMsg.Text = "OnUpdateImage: Xong";
    }

    protected void OnAction9(object sender, EventArgs e)
    {
        //cap nhat other sortname cho book de phuc vu quick search
        using (var context = new CmsDataContext())
        {
            var all = context.Books.Where(x => x.OtherSortName == null).ToList();
            foreach (var item in all)
            {
                var sort = BaseObject.GetSortName(item.OtherName);
                if (sort.Length == 0) sort = item.SortName;
                context.ExecuteCommand("update Book set OtherSortName={0} Where Id={1}", sort, item.ID);
            }
        }
        ltrMsg.Text = "cap nhat other sortname: Xong";
    }

    protected void OnAction10(object sender, EventArgs e)
    {
        //Cap nhat Content o cac do main chua dinh nghia luc crawler
        using (var context = new CmsDataContext())
        {
            var all = context.Contents.Where(x => !x.Finish && !x.CrawlUrl.StartsWith("http://blogtruyen.com") && !x.CrawlUrl.StartsWith("http://comicvn.net")).ToList();
            foreach (var item in all)
            {
                var body = Portal.Data.Crawler.Common.GetChapBody(item.CrawlUrl);
                if (body.Length > 0)
                {
                    Content.SetBody(item.Book_ID, item.ID, body);
                    var bodyMobile = Content.ConvertToMobileBody(body);
                    Content.SetBodyMobile(item.Book_ID, item.ID, bodyMobile);
                    context.ExecuteCommand("update Content set Finish=1 Where Content_ID={0}", item.ID);
                }
            }
        }
        ltrMsg.Text = "Cap nhat Content o cac do main chua dinh nghia luc crawler: Xong";
    }
}